// 角色

const { AclRole, AclRolePermission, Sequelize } = require('../models')
const Page = require('../modules/page')

/**
 * 获取角色page或list
 *
 * @param {Object} conditions
 * @param {Object} param1
 */
module.exports.list = async function (conditions, page = new Page()) {
  const where = {}
  const count = await AclRole.count({ where })

  let options = {
    attributes: { exclude: ['deleteTime'] },
    where,
  }
  if (page.size > 0) {
    Object.assign(options, {
      limit: page.size,
      offset: (page.number - 1) * page.size,
    })
  }

  const data = await AclRole.findAll(options)

  return {
    total: count,
    pagenum: page.number,
    list: data.map((role) => role.toJSON()),
  }
}

module.exports.create = async function (role) {
  const res = await AclRole.create(role)
  return res.toJSON()
}

module.exports.update = async function (role) {
  const roleDb = await AclRole.findByPk(role.id)
  await roleDb.update(role)
  return roleDb.toJSON()
}

module.exports.getById = async function (id) {
  const role = await AclRole.findByPk(id, {
    attributes: { exclude: ['deleteTime'] },
    include: {
      model: AclRolePermission,
      as: 'perms',
    },
  })
  if (role != null) {
    return role.toJSON()
  } else {
    throw new Error('角色不存在！')
  }
}

module.exports.delete = async function (id) {
  const result = await Sequelize.transaction(async (t) => {
    const res = await AclRole.destroy({ where: { id }, transaction: t })
    await AclRolePermission.destroy({ where: { role_id: id }, transaction: t })
    return res
  })
  return result
}

module.exports.updatePerms = async function (id, perms, cb) {
  const data = perms.map((perm) => {
    return { role_id: id, permission_id: perm.id, type: perm.type }
  })
  const result = await Sequelize.transaction(async (t) => {
    await AclRolePermission.destroy({
      where: { role_id: id },
      transaction: t,
    })
    const res = await AclRolePermission.bulkCreate(data, {
      transaction: t,
    })
    return res.length
  })
  return result
}
